import { routerRedux } from 'dva/router';
import { Toast } from 'antd-mobile';
import _ from 'lodash';
import moment from 'moment';
import * as couponService from '../services/couponService';

const delay = (time) => {
  return new Promise((rs) => {
    setTimeout(rs, time);
  });
};

export default {
  namespace: 'coupon',
  state: {
    couponCode: {},
    coupon: {},
    codeList: [],
    couponList: [],
    meta: {},
  },
  effects: {
    * toUsePage({ payload }, { call, put }) {
      yield put(routerRedux.push({
        pathname: '/couponUse',
      }));
    },
    * toHistoryPage({ payload }, { call, put }) {
      yield put(routerRedux.push({
        pathname: '/couponHistory',
      }));
    },
    * searchCouponCode({ payload }, { call, put, select }) {
      const { shopId } = yield select(state => state.auth.currentUser);
      let code = payload.code;
      if (_.startsWith(code, 'h')) {
        code = 'h' + code.substring(1);
      }
      let result = yield call(couponService.searchCouponCode, shopId, { filter: { code } });
      if (result && result.data) {
        if (result.data.length > 0) {
          const couponCode = result.data[0];
          result = yield call(couponService.searchCoupon, shopId, { filter: { couponId: couponCode.couponId } });
          const coupon = result.data[0];
          if (!coupon) {
            setTimeout(() => {
              Toast.fail('未找到对应的优惠券', 2);
            }, 1);
          } else {
            let expired = false;
            if (couponCode && couponCode.status === 3) {
              expired = true;
            } else if (coupon) {
              const endDate = moment(coupon.endDate).endOf('day');
              if (endDate && moment().isAfter(endDate)) {
                expired = true;
              }
            }
            if (expired) {
              setTimeout(() => {
                Toast.fail('无法核销，请在优惠券有效期内使用', 3);
              }, 1);
            } else {
              yield put({ type: 'searchCodeSuccess', payload: { couponCode, coupon } });
              yield put(routerRedux.push({
                pathname: '/couponCode',
              }));
            }
          }
        } else {
          setTimeout(() => {
            Toast.fail('未找到对应的优惠券码', 2);
          }, 1);
        }
      }
    },
    * useCouponCode({ payload }, { call, put, select }) {
      const { shopId, branchNo, branchId, salemanId, saleManName, _id: userId, phone, username } = yield select(state => state.auth.currentUser);
      const { couponCode } = yield select(state => state.coupon);
      if (couponCode) {
        const data = {
          status: 2,
          flow_no: payload.flow_no,
          useData: {
            userId,
            use_date: new Date(),
            branch_no: branchId || branchNo,
            saleman_id: salemanId,
            saleman_name: saleManName,
            phone,
            username,
          },
        };
        const result = yield call(couponService.updateCouponCode, shopId, couponCode._id, data);
        if (result && result.data) {
          yield put({ type: 'useCodeSuccess', payload: { couponCode: result.data } });
          setTimeout(() => {
            Toast.success('成功使用优惠券', 2);
          }, 1);
        } else {
          setTimeout(() => {
            Toast.fail('未找到对应的优惠券', 2);
          }, 1);
        }
      } else {
        setTimeout(() => {
          Toast.fail('未找到对应的优惠券', 2);
        }, 1);
      }
    },
    * back({ payload }, { call, put, select }) {
      yield put(routerRedux.push({
        pathname: '/',
      }));
    },
    * initHistory({ payload }, { call, put, select }) {
      const { shopId, roles, salemanId } = yield select(state => state.auth.currentUser);
      let params;
      if (_.includes(roles, 'operator') || _.includes(roles, 'boss')) {
        params = { filter: { saleman_id: { $exists: true, $ne: null } } };
      } else if (salemanId) {
        params = { filter: { saleman_id: salemanId } };
      }
      if (payload.filter) {
        params.filter = params.filter || {};
        params.filter = { ...params.filter, ...payload.filter };
      }
      if (params) {
        params.pageSize = payload.pageSize || 20;
        params.page = 1;
        const codeResult = yield call(couponService.searchCouponCode, shopId, params);
        if (codeResult && codeResult.data && codeResult.data.length > 0) {
          const couponResult = yield call(couponService.searchCoupon, shopId, { pageSize: 500 });
          yield put({ type: 'searchHistorySuccess', payload: { meta: codeResult.meta, codeList: codeResult.data, couponList: couponResult.data } });
        }
      }
    },
    * nextPageHistory({ payload }, { call, put, select }) {
      const { shopId, roles, salemanId } = yield select(state => state.auth.currentUser);
      const { page } = yield select(state => state.coupon.meta);
      let params;
      if (_.includes(roles, 'operator') || _.includes(roles, 'boss')) {
        params = { filter: { saleman_id: { $exists: true, $ne: null } } };
      } else if (salemanId) {
        params = { filter: { saleman_id: salemanId } };
      }
      if (params) {
        params.pageSize = 20;
        params.page = (parseInt(page, 10) || 0) + 1;
        const codeResult = yield call(couponService.searchCouponCode, shopId, params);
        if (codeResult && codeResult.data && codeResult.data.length > 0) {
          yield put({ type: 'searchHistorySuccess', payload: { meta: codeResult.meta, codeList: codeResult.data } });
        }
      }
    },
    * fetchVipCouponCodes({ payload }, { call, put, select }) {
      const { shopId } = yield select(state => state.auth.currentUser);
      const card_id = payload.card_id || payload.cardNo;
      const params = {
        pageSize: 200,
        filter: { card_id, status: 1 },
      };
      const codeResult = yield call(couponService.searchCouponCode, shopId, params);
      if (codeResult && codeResult.data && codeResult.data.length > 0) {
        const couponResult = yield call(couponService.searchCoupon, shopId, { pageSize: 500 });
        yield put({ type: 'searchHistorySuccess', payload: { meta: codeResult.meta, codeList: codeResult.data, couponList: couponResult.data } });
      }
    },
    * fetchShopCoupons({ payload }, { call, put, select }) {
      const { shopId } = yield select(state => state.auth.currentUser);
      const params = {
        pageSize: 200,
        filter: { shopId, status: { $in: [1] }, sendType: { $in: [3] } },
      };
      const couponResult = yield call(couponService.searchCoupon, shopId, params);
      yield put({ type: 'searchHistorySuccess', payload: { meta: couponResult.meta, couponList: couponResult.data } });
    },
    * sendCoupon({ payload }, { call, put, select }) {
      const { shopId, salemanId: saleman_id, saleManName: saleman_name } = yield select(state => state.auth.currentUser);
      const { coupon: { _id: id }, card_id } = payload;
      if (id && card_id) {
        const result = yield call(couponService.sendCoupon, shopId, id, card_id, saleman_id, saleman_name);
        console.log(result);
        if (result && result.data) {
          setTimeout(() => {
            Toast.success('成功发送优惠券', 2);
          }, 1);
        } else {
          setTimeout(() => {
            Toast.fail('未找到对应的优惠券', 2);
          }, 1);
        }
      } else {
        setTimeout(() => {
          Toast.fail('未找到对应的优惠券', 2);
        }, 1);
      }
    },
  },
  reducers: {
    init(state, { payload }) {
      return { ...state, couponCode: {}, coupon: {}, couponList: [], codeList: [] };
    },
    searchCodeSuccess(state, { payload }) {
      return { ...state, couponCode: payload.couponCode, coupon: payload.coupon };
    },
    useCodeSuccess(state, { payload }) {
      return { ...state, couponCode: payload.couponCode };
    },
    searchHistorySuccess(state, { payload }) {
      return {
        ...state,
        meta: { ...state.meta, ...payload.meta },
        codeList: payload.meta.page > 1 ? [...(state.codeList), ...(payload.codeList)] : [...(payload.codeList || state.codeList)],
        couponList: [...(payload.couponList || state.couponList)],
      };
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname, query }) => {
        if (pathname === '/coupon') {
          dispatch({
            type: 'init',
            payload: {},
          });
        }
        if (pathname === '/couponUse') {
          dispatch({
            type: 'init',
            payload: {},
          });
        }
        if (pathname === '/p1_info') {
          dispatch({
            type: 'init',
            payload: {},
          });
        }
        if (pathname === '/vipInfo') {
          dispatch({
            type: 'init',
            payload: {},
          });
          dispatch({
            type: 'fetchShopCoupons',
            payload: {},
          });
          const cardNo = query.cardId || query.cardNo;
          if (cardNo) {
            dispatch({
              type: 'fetchVipCouponCodes',
              payload: { card_id: cardNo },
            });
          }
        }
        if (pathname === '/couponHistory') {
          dispatch({
            type: 'initHistory',
            payload: {},
          });
        }
      });
    },
  },
};
